package cn.calm.xhtml.impl;

import java.net.URL;

import cn.calm.xhtml.api.TemplateLoader;

public class ClassPathTemplateLoader implements TemplateLoader {
	private String prefix;
	private ClassLoader classLoader;

	public ClassPathTemplateLoader() {
		classLoader = ClassPathTemplateLoader.class.getClassLoader();
	}

	public ClassPathTemplateLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	public ClassPathTemplateLoader(ClassLoader classLoader, String prefix) {
		this.classLoader = classLoader;
		this.prefix = prefix;
	}

	@Override
	public URL loadTemplate(String template) {
		if (template == null) {
			throw new RuntimeException("template is null");
		}
		if (classLoader == null) {
			throw new RuntimeException("classLoader is null");
		}
		String temp = getPrefix() + template;
		if (!temp.startsWith("/")) {
			temp = "/" + temp;
		}
		temp = temp.replaceAll("//", "/");
		URL resource = ClassPathTemplateLoader.class.getResource(temp);
		return resource;
	}

	public String getPrefix() {
		if (prefix == null) {
			prefix = "";
		}
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

}
